package org.csu.mypetstorecmsapi.service;

import org.csu.mypetstorecmsapi.domain.Admin;
import org.csu.mypetstorecmsapi.persistence.AdminDao;
import org.csu.mypetstorecmsapi.util.Md5Util;
import org.csu.mypetstorecmsapi.util.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Optional;

@Service
public class AdminService {

    @Autowired
    private AdminDao adminDao;

    public Admin getAdminByUsername(String username) {
        Optional<Admin> a = adminDao.findAll().stream().filter(admin -> admin.getUsername().equals(username)).findFirst();
        return a.orElse(null);  //返回Admin对象
    }

    public void register(String username, String password) {
        //MD5加密
        String md5String = Md5Util.getMD5String(password);

        //在管理员表里添加一条记录
        Admin admin = new Admin();
        admin.setUsername(username);
        admin.setPassword(md5String);
        adminDao.save(admin);
    }

    public void updatePassword(String newPwd) {
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        Optional<Admin> a = adminDao.findAll().stream().filter(admin -> admin.getUsername().equals(username)).findFirst();
        a.get().setPassword(Md5Util.getMD5String(newPwd));
        adminDao.save(a.get());
    }
}
